package com.yoomiito.app.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Typeface;
import android.os.Build;
import androidx.appcompat.app.AppCompatActivity;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.Log;

import com.google.zxing.WriterException;
import com.tbruyelle.rxpermissions2.Permission;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yoomiito.app.Constant;
import com.yoomiito.app.R;
import com.yoomiito.app.base.App;
import com.yoomiito.app.ui.account.LoginActivity;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.droidlover.xdroidmvp.cache.SharedPref;
import cn.droidlover.xdroidmvp.router.Router;
import io.reactivex.Observable;

public class AllUtils {

    public static void copyText(Context context, String s) {
        if (!TextUtils.isEmpty(s)) {
            //获取剪贴板管理器：
            ClipboardManager cm = (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
            // 创建普通字符型ClipData
            ClipData mClipData = ClipData.newPlainText("Label", s);
            // 将ClipData内容放到系统剪贴板里。
            cm.setPrimaryClip(mClipData);
        }
    }

    public static String getClipbordContent() {
        ClipboardManager cm = (ClipboardManager) App.getInstance().getSystemService(Context.CLIPBOARD_SERVICE);
        ClipData data = cm.getPrimaryClip();
        if (data == null) return "";
        ClipData.Item item = data.getItemAt(0);
        if (item == null) return "";
        if (item.getText() == null) return "";
        return item.getText().toString();
    }

    public static void toLogin(Activity context, String type) {
        SharedPref.getInstance(App.getInstance()).putBoolean(Constant.IS_LOGIN, false);
        SharedPref.getInstance(App.getInstance()).remove(Constant.TOKEN);
        SharedPref.getInstance(App.getInstance()).remove(Constant.RoleId);
        SharedPref.getInstance(App.getInstance()).remove(Constant.CompanyId);
        SharedPref.getInstance(App.getInstance()).remove(Constant.INVITE_CODE);
        Router.newIntent(context)
                .putString(Constant.TYPE, type)
                .to(LoginActivity.class)
                .launch();
    }

    public static Observable<Boolean> requestPermission(AppCompatActivity context, String... permissions) {
        RxPermissions rxPermissions = new RxPermissions(context);
        return rxPermissions.request(permissions);
    }

    public static String permissionTipMap(String permission) {
        switch (permission) {
              case Manifest.permission.READ_EXTERNAL_STORAGE:
            case Manifest.permission.WRITE_EXTERNAL_STORAGE:
                return "存储权限:上传手机图片，保存文件至手机，发送图片时，需要开启存储权限以便上传和存储图片。";
            case Manifest.permission.CAMERA:
                return "相机权限:在向您提供头像设置，拍摄图片时，您可以开启相机权限以便拍摄图片。";
            case Manifest.permission.READ_CONTACTS:
                return "读取通讯录：获取您的联系人姓名及手机号，用于填写收货地址处，便于商品交付配送。";
            default:
                return "";
        }
    }

    public static Observable<Permission> requestPermission2(AppCompatActivity context, String... permissions) {
        RxPermissions rxPermissions = new RxPermissions(context);
        return rxPermissions.requestEach(permissions);
    }

    public static Observable<Permission> requestPermission3(AppCompatActivity context, String... permissions) {
        RxPermissions rxPermissions = new RxPermissions(context);
        return rxPermissions.requestEachCombined(permissions);
    }

    /**
     * @return
     */
    public static PackageInfo getVersionInfo() {
        PackageManager pm = App.getInstance().getPackageManager();
        try {
            return pm.getPackageInfo(App.getInstance().getPackageName(), 0);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean haveInstallApk() {
        PackageManager pm = App.getInstance().getPackageManager();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            return pm.canRequestPackageInstalls();
        }
        return true;
    }

    public static String telHandle(String tel) {
        if (TextUtils.isEmpty(tel)) return "";
        String start = tel.substring(0, 3);
        String end = tel.substring(7, 11);
        return start + "****" + end;
    }

    /**
     * 获取设备信息
     * 在6.0一下的机型可以通过Android_id→device_id→uuid来获取唯一标识
     * 在6.0以上为了避免权限问题则不通过device_id来确认信息。
     */
    @SuppressLint({"HardwareIds", "MissingPermission"})
    public static void getDeviceInfo(Context context) {
        try {
            String device_id;
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
                device_id = android.provider.Settings.Secure.getString(
                        context.getContentResolver(),
                        android.provider.Settings.Secure.ANDROID_ID);
                if (TextUtils.isEmpty(device_id)) {
                    android.telephony.TelephonyManager tm = (android.telephony.TelephonyManager) context
                            .getSystemService(Context.TELEPHONY_SERVICE);
                    device_id = tm.getDeviceId();
                }
                SharedPref.getInstance(App.getApplication()).putString(Constant.DEVICE_ID, device_id);
            } else {
//                device_id = android.provider.Settings.Secure.getString(
//                        context.getContentResolver(),
//                        android.provider.Settings.Secure.ANDROID_ID);
                AllUtils.requestPermission((AppCompatActivity) context, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                        Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.READ_PHONE_STATE)
                        .subscribe(aBoolean -> {
                            if (aBoolean) getDeviceId((Activity) context);
                        });
            }
//            if (TextUtils.isEmpty(device_id) || device_id.equals("9774d56d682e549c")) {
//                device_id = Installation.id(context);
//            }
//            return device_id;
        } catch (Exception e) {
            e.printStackTrace();
        }
//        return "";
    }

    public static String getDeviceId(Activity context) {
        String id;
        TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {//8.0以上
            id = tm.getMeid();
        } else {//(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
            id = tm.getDeviceId();
        }

        SharedPref.getInstance(App.getApplication()).putString(Constant.DEVICE_ID, id);
        return id;
    }

    /**
     * 应用是否位于前台
     *
     * @param context
     * @return
     */
    public static boolean isApplicationInBackground(Context context) {
        if (context == null) {
            return false;
        }
//        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
//        List<ActivityManager.RunningTaskInfo> taskList = am.getRunningTasks(1);
//        if (taskList != null && !taskList.isEmpty()) {
//            ComponentName topActivity = taskList.get(0).topActivity;
//            if (topActivity != null && !topActivity.getPackageName().equals(context.getPackageName())) {
//                return true;
//            }
//        }
//        return false;
        ActivityManager activityManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> appProcesses = activityManager
                .getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo appProcess : appProcesses) {
            if (appProcess.processName.equals(context.getPackageName())) {
                /*
                BACKGROUND=400 EMPTY=500 FOREGROUND=100
                GONE=1000 PERCEPTIBLE=130 SERVICE=300 ISIBLE=200
                 */
                Log.i(context.getPackageName(), "此appimportace ="
                        + appProcess.importance
                        + ",context.getClass().getName()="
                        + context.getClass().getName());
                if (appProcess.importance != ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                    Log.i(context.getPackageName(), "处于后台"
                            + appProcess.processName);
                    return true;
                } else {
                    Log.i(context.getPackageName(), "处于前台"
                            + appProcess.processName);
                    return false;
                }
            }
        }
        return false;
    }

    private static long lastClickTime = 0;//上次点击的时间
    private static int spaceTime = 1000;//时间间隔

    //防止双击
    public static boolean isFastClick() {

        long currentTime = System.currentTimeMillis();//当前系统时间
        boolean isAllowClick;//是否允许点击
        L.i("点击1 " + currentTime + "  " + lastClickTime);

        if (currentTime - lastClickTime > spaceTime) {
            L.i("点击2");

            isAllowClick = false;
        } else {
            L.i("点击3");

            isAllowClick = true;
        }

        lastClickTime = currentTime;
        return isAllowClick;
    }

    /**
     * 乘
     *
     * @param price
     * @param size
     * @return
     */
    public static String priceMul_2(String price, int size) {
        BigDecimal bd1 = new BigDecimal(price);
        BigDecimal bd2 = new BigDecimal(size);

        return bd1.multiply(bd2).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }

    /**
     * 乘
     *
     * @param price
     * @param size
     * @return
     */
    public static String priceMul(String price, int size) {
        BigDecimal bd1 = new BigDecimal(price);
        BigDecimal bd2 = new BigDecimal(size);
        return bd1.multiply(bd2).toString();
    }

    /**
     * 除法 value1除以value2
     * @param value1
     * @param value2
     * @return
     */
    public static String priceDiv(String value1, String value2) {
        BigDecimal bd1 = new BigDecimal(value1);
        BigDecimal bd2 = new BigDecimal(value2);
        return bd1.divide(bd2).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }

    /**
     * 加 保留2位小数
     *
     * @param data1
     * @param data2
     * @return
     */
    public static String priceSum_2(String data1, String data2) {
        BigDecimal bd1 = new BigDecimal(data1);
        BigDecimal bd2 = new BigDecimal(data2);
        return bd1.add(bd2).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }

    /**
     * 减
     *
     * @param data1
     * @param data2
     * @return
     */
    public static String priceSub(String data1, String data2) {
        BigDecimal bd1 = new BigDecimal(data1);
        BigDecimal bd2 = new BigDecimal(data2);
        return bd1.subtract(bd2).toString();
    }

    /**
     * 减 保留2位小数
     * @param data1
     * @param data2
     * @return
     */
    public static String priceSub_2(String data1, String data2) {
        BigDecimal bd1 = new BigDecimal(data1);
        BigDecimal bd2 = new BigDecimal(data2);
        return bd1.subtract(bd2).setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }

    public static String price_2(String data) {
        BigDecimal bd1 = new BigDecimal(data);
        return bd1.setScale(2, BigDecimal.ROUND_HALF_UP).toString();
    }

    /**
     * @param str1
     * @param str2
     * @return true 大于等于 false 小于
     */
    public static boolean moneyCompare(String str1, String str2) {
        BigDecimal bd1 = new BigDecimal(str1);
        BigDecimal bd2 = new BigDecimal(str2);
        int flag = bd1.compareTo(bd2);
        if (flag >= 0) {
            return true;
        }
        return false;
    }

    public static boolean moneyCompare1(String str1, String str2) {
        BigDecimal bd1 = new BigDecimal(str1);
        BigDecimal bd2 = new BigDecimal(str2);
        int flag = bd1.compareTo(bd2);
        if (flag > 0) {
            return true;
        }
        return false;
    }

    public static Bitmap makeErWeiMa(Resources resources, int resColor, String url) {
        Bitmap bitmap = BitmapFactory.decodeResource(resources, R.drawable.app_launcher, null);
        try {
            return ZxingUtil.cretaeZxing(url, bitmap, resources.getColor(resColor));
        } catch (WriterException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static Typeface getTypeface() {
        return Typeface.createFromAsset(App.getApplication().getAssets(), "font/DIN Condensed Bold.woff.ttf");
    }

    /**
     * 获取指定对象的多个变量值
     *
     * @param t
     * @param keys
     * @param <T>
     * @return
     */
    public static <T> Map<String, String> getMemberValue(T t, String[] keys) {
        if(null==t){
            return null;
        }
        Map<String, String> map = new HashMap<>();
        Class s = t.getClass();
        Field[] fs = s.getDeclaredFields();
        for (String key : keys) {
            for (Field f : fs) {
                f.setAccessible(true);
                if (key.equals(f.getName())) {
                    try {
                        map.put(key, f.get(t) + "");
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                    break;
                }

            }
        }
        return map;
    }

    public static <T> String getMemberValue(T t, String key) {
        Class s = t.getClass();
        Field[] fs = s.getDeclaredFields();
        for (Field f : fs) {
            f.setAccessible(true);
            if (key.equals(f.getName())) {
                try {
                    return f.get(t) + "";
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

}
